package com.yzkj.cpjxc.business.framework.tld;

import com.yzkj.cpjxc.business.domain.SysAuthority;
import com.yzkj.cpjxc.business.domain.SysUser;
import com.yzkj.cpjxc.business.framework.common.Constants;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.List;

/**
 * 权限标签 
 * TODO javadoc for com.chkj.framework.tld.PermissionTag
 */
public class PermissionTag extends TagSupport {

	private static final long serialVersionUID = -2641723708977239210L;

	private String privilege;

	public String getPrivilege() {
		return privilege;
	}

	public void setPrivilege(String privilege) {
		this.privilege = privilege;
	}

	@Override
	public int doStartTag() throws JspException {
		SysUser sysUser = (SysUser) (((HttpServletRequest) pageContext.getRequest()).getSession().getAttribute(Constants.CURRENT_USER));
		if (sysUser != null) {
			List<SysAuthority> authSet = sysUser.getSysAuthoritys();
			boolean result = false;
			if (!StringUtils.contains(privilege, ",")) {
				result = hasPrivilege(authSet, privilege);
			} else {
				String[] privileges = StringUtils.split(privilege, ",");
				for (String p : privileges) {
					result = result || hasPrivilege(authSet, StringUtils.trim(p));
				}
			}
			return result ? EVAL_BODY_INCLUDE : SKIP_BODY;
		}
		return SKIP_BODY;
	}

	/**
	 * 判断当前用户的权限里面是否包含所访问的权限，有：返回true,否：返回false
	 */
	private boolean hasPrivilege(List<SysAuthority> authSet, String authName) {
		for(SysAuthority sysAuthority: authSet){
			if(sysAuthority.getAuthorityValue().equals(authName)){
				return true;
			}
		}
		return false;
	}

}
